<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { IconifyIcon } from '@vben/icons';

import { Empty, Input, Modal, TabPane, Tabs } from 'ant-design-vue';
import { Search } from 'lucide-vue-next';

interface Props {
  value?: string;
}

const props = defineProps<Props>();
const emit = defineEmits(['update:value', 'change']);

const visible = ref(false);
const searchText = ref('');
const selectedIcon = ref('');
const activeTab = ref('lucide');

// 常用图标库
const iconSets = {
  lucide: {
    name: 'Lucide',
    prefix: 'lucide',
    icons: [
      // 基础图标
      'home',
      'user',
      'users',
      'settings',
      'menu',
      'folder',
      'file',
      'file-text',
      'layout',
      'layout-dashboard',
      'layout-grid',
      'layout-list',
      'box',
      'package',
      'shopping-cart',
      'shopping-bag',
      'credit-card',
      'dollar-sign',
      'trending-up',
      'trending-down',
      'bar-chart',
      'pie-chart',
      'activity',
      'calendar',
      'clock',
      'bell',
      'mail',
      'message-square',
      'phone',
      'video',
      'image',
      'camera',
      'map',
      'map-pin',
      'navigation',
      'compass',
      'star',
      'heart',
      'bookmark',
      'tag',
      'flag',
      'shield',
      'lock',
      'unlock',
      'key',
      'eye',
      'eye-off',
      'search',
      'filter',
      'edit',
      'edit-2',
      'edit-3',
      'trash',
      'trash-2',
      'plus',
      'minus',
      'x',
      'check',
      'chevron-right',
      'chevron-left',
      'chevron-up',
      'chevron-down',
      'arrow-right',
      'arrow-left',
      'arrow-up',
      'arrow-down',
      'download',
      'upload',
      'refresh-cw',
      'rotate-cw',
      'save',
      'copy',
      'clipboard',
      'share',
      'link',
      'external-link',
      'maximize',
      'minimize',
      'zoom-in',
      'zoom-out',
      'info',
      'alert-circle',
      'alert-triangle',
      'help-circle',
      'check-circle',
      'x-circle',
      // 工作流相关图标
      'workflow',
      'git-branch',
      'git-merge',
      'git-pull-request',
      'git-commit',
      'network',
      'share-2',
      'shuffle',
      'repeat',
      'repeat-1',
      'rotate-ccw',
      'play',
      'pause',
      'stop-circle',
      'skip-forward',
      'skip-back',
      'fast-forward',
      'rewind',
      'play-circle',
      'pause-circle',
      // 状态和标记
      'circle',
      'circle-dot',
      'check-square',
      'square',
      'octagon',
      'hexagon',
      'triangle',
      'diamond',
      'loader',
      'loader-2',
      'hourglass',
      'timer',
      'alarm-clock',
      // 文档和文件
      'file-check',
      'file-x',
      'file-plus',
      'file-minus',
      'file-edit',
      'file-search',
      'file-archive',
      'file-code',
      'file-json',
      'files',
      'folder-open',
      'folder-plus',
      'folder-minus',
      'folder-check',
      'folder-x',
      // 数据和分析
      'database',
      'server',
      'hard-drive',
      'cpu',
      'monitor',
      'smartphone',
      'tablet',
      'laptop',
      'terminal',
      'code',
      'code-2',
      'brackets',
      'braces',
      'git-branch-plus',
      'git-compare',
      'git-fork',
    ],
  },
  ep: {
    name: 'Element Plus',
    prefix: 'ep',
    icons: [
      // 基础图标
      'home',
      'user',
      'setting',
      'menu',
      'folder',
      'document',
      'grid',
      'list',
      'box',
      'goods',
      'shopping-cart',
      'shopping-bag',
      'credit-card',
      'coin',
      'data-line',
      'data-board',
      'data-analysis',
      'calendar',
      'clock',
      'bell',
      'message',
      'chat-dot-round',
      'phone',
      'video-camera',
      'picture',
      'camera',
      'location',
      'position',
      'guide',
      'star',
      'collection',
      'price-tag',
      'flag',
      'lock',
      'unlock',
      'key',
      'view',
      'hide',
      'search',
      'filter',
      'edit',
      'delete',
      'plus',
      'minus',
      'close',
      'check',
      'arrow-right',
      'arrow-left',
      'arrow-up',
      'arrow-down',
      'download',
      'upload',
      'refresh',
      'sort',
      'files',
      'share',
      'link',
      'zoom-in',
      'zoom-out',
      'info-filled',
      'warning-filled',
      'question-filled',
      'success-filled',
      'circle-close-filled',
      // 工作流相关
      'connection',
      'share',
      'promotion',
      'switch',
      'operation',
      'finished',
      'circle-check',
      'circle-close',
      'warning',
      'timer',
      'loading',
      'refresh-left',
      'refresh-right',
      'sort-up',
      'sort-down',
      'rank',
      'trend-charts',
      'histogram',
      'pie-chart',
      'data-analysis',
      'management',
      'monitor',
      'tools',
      'setting',
      'coordinate',
      'magic-stick',
      'tickets',
      'document-add',
      'document-checked',
      'document-copy',
      'document-delete',
      'document-remove',
      'folder-add',
      'folder-checked',
      'folder-delete',
      'folder-opened',
      'folder-remove',
      'notebook',
      'reading',
      'memo',
      'postcard',
      'stamp',
      'collection-tag',
      'flag',
      'present',
      'box',
      'briefcase',
      'suitcase',
      'files',
      'notebook',
      'reading',
      'data-board',
      'platform',
      'odometer',
      'aim',
      'cpu',
      'discover',
      'place',
      'location-information',
      'add-location',
      'delete-location',
      'map-location',
      'office-building',
      'school',
      'toilet-paper',
      'house',
      'table-lamp',
      'film',
      'suitcase-line',
      'notebook-2',
      'reading-lamp',
      'office-building',
      'school',
    ],
  },
  mdi: {
    name: 'Material Design',
    prefix: 'mdi',
    icons: [
      // 基础图标
      'home',
      'account',
      'account-group',
      'cog',
      'menu',
      'folder',
      'file',
      'file-document',
      'view-dashboard',
      'view-grid',
      'view-list',
      'package-variant',
      'cart',
      'shopping',
      'credit-card',
      'currency-usd',
      'chart-line',
      'chart-bar',
      'chart-pie',
      'calendar',
      'clock',
      'bell',
      'email',
      'message',
      'phone',
      'video',
      'image',
      'camera',
      'map',
      'map-marker',
      'navigation',
      'star',
      'heart',
      'bookmark',
      'tag',
      'flag',
      'shield',
      'lock',
      'lock-open',
      'key',
      'eye',
      'eye-off',
      'magnify',
      'filter',
      'pencil',
      'delete',
      'plus',
      'minus',
      'close',
      'check',
      'chevron-right',
      'chevron-left',
      'chevron-up',
      'chevron-down',
      'arrow-right',
      'arrow-left',
      'arrow-up',
      'arrow-down',
      'download',
      'upload',
      'refresh',
      'content-save',
      'content-copy',
      'share',
      'link',
      'open-in-new',
      'fullscreen',
      'fullscreen-exit',
      'magnify-plus',
      'magnify-minus',
      'information',
      'alert-circle',
      'alert',
      'help-circle',
      'check-circle',
      'close-circle',
      // 工作流相关
      'workflow',
      'source-branch',
      'source-merge',
      'source-pull',
      'source-commit',
      'git',
      'github',
      'gitlab',
      'bitbucket',
      'vector-polyline',
      'vector-line',
      'vector-point',
      'vector-circle',
      'vector-square',
      'vector-triangle',
      'sitemap',
      'lan',
      'network',
      'swap-horizontal',
      'swap-vertical',
      'shuffle',
      'repeat',
      'repeat-once',
      'sync',
      'sync-alert',
      'sync-circle',
      'autorenew',
      'cached',
      'restore',
      'history',
      'timeline',
      'timeline-text',
      'timeline-clock',
      'timeline-alert',
      'timeline-check',
      'timeline-plus',
      'timeline-remove',
      'state-machine',
      'chart-timeline',
      'chart-gantt',
      'chart-tree',
      'chart-sankey',
      'chart-waterfall',
      'chart-arc',
      'chart-donut',
      'chart-bubble',
      'chart-scatter-plot',
      'chart-bell-curve',
      'progress-check',
      'progress-clock',
      'progress-download',
      'progress-upload',
      'checkbox-marked-circle',
      'checkbox-marked-circle-outline',
      'checkbox-blank-circle',
      'checkbox-blank-circle-outline',
      'radiobox-marked',
      'radiobox-blank',
      'circle-slice-1',
      'circle-slice-2',
      'circle-slice-3',
      'circle-slice-4',
      'circle-slice-5',
      'circle-slice-6',
      'circle-slice-7',
      'circle-slice-8',
      'play',
      'pause',
      'stop',
      'skip-next',
      'skip-previous',
      'fast-forward',
      'rewind',
      'play-circle',
      'pause-circle',
      'stop-circle',
    ],
  },
  antd: {
    name: 'Ant Design',
    prefix: 'ant-design',
    icons: [
      // 方向性图标
      'step-backward',
      'step-forward',
      'fast-backward',
      'fast-forward',
      'shrink',
      'arrows-alt',
      'down',
      'up',
      'left',
      'right',
      'caret-up',
      'caret-down',
      'caret-left',
      'caret-right',
      'up-circle',
      'down-circle',
      'left-circle',
      'right-circle',
      'double-right',
      'double-left',
      'vertical-left',
      'vertical-right',
      'vertical-align-top',
      'vertical-align-middle',
      'vertical-align-bottom',
      'forward',
      'backward',
      'rollback',
      'enter',
      'retweet',
      'swap',
      'swap-left',
      'swap-right',
      'arrow-up',
      'arrow-down',
      'arrow-left',
      'arrow-right',
      'play-circle',
      'up-square',
      'down-square',
      'left-square',
      'right-square',
      'login',
      'logout',
      'menu-fold',
      'menu-unfold',
      'border-bottom',
      'border-horizontal',
      'border-inner',
      'border-outer',
      'border-left',
      'border-right',
      'border-top',
      'border-verticle',
      'pic-center',
      'pic-left',
      'pic-right',
      'radius-bottomleft',
      'radius-bottomright',
      'radius-upleft',
      'radius-upright',
      'fullscreen',
      'fullscreen-exit',
      // 提示建议性图标
      'question',
      'question-circle',
      'plus',
      'plus-circle',
      'pause',
      'pause-circle',
      'minus',
      'minus-circle',
      'plus-square',
      'minus-square',
      'info',
      'info-circle',
      'exclamation',
      'exclamation-circle',
      'close',
      'close-circle',
      'close-square',
      'check',
      'check-circle',
      'check-square',
      'clock-circle',
      'warning',
      'issues-close',
      'stop',
      // 编辑类图标
      'edit',
      'form',
      'copy',
      'scissor',
      'delete',
      'snippets',
      'diff',
      'highlight',
      'align-center',
      'align-left',
      'align-right',
      'bg-colors',
      'bold',
      'italic',
      'underline',
      'strikethrough',
      'redo',
      'undo',
      'zoom-in',
      'zoom-out',
      'font-colors',
      'font-size',
      'line-height',
      'dash',
      'small-dash',
      'sort-ascending',
      'sort-descending',
      'drag',
      'ordered-list',
      'unordered-list',
      'radius-setting',
      'column-width',
      'column-height',
      // 数据类图标
      'area-chart',
      'pie-chart',
      'bar-chart',
      'dot-chart',
      'line-chart',
      'radar-chart',
      'heat-map',
      'fall',
      'rise',
      'stock',
      'box-plot',
      'fund',
      'sliders',
      // 品牌和标识
      'android',
      'apple',
      'windows',
      'ie',
      'chrome',
      'github',
      'aliwangwang',
      'dingding',
      'weibo-square',
      'weibo-circle',
      'taobao-circle',
      'html5',
      'weibo',
      'twitter',
      'wechat',
      'youtube',
      'alipay-circle',
      'taobao',
      'skype',
      'qq',
      'medium-workmark',
      'gitlab',
      'medium',
      'linkedin',
      'google-plus',
      'dropbox',
      'facebook',
      'codepen',
      'code-sandbox',
      'amazon',
      'google',
      'codepen-circle',
      'alipay',
      'ant-design',
      'ant-cloud',
      'aliyun',
      'zhihu',
      'slack',
      'slack-square',
      'behance',
      'behance-square',
      'dribbble',
      'dribbble-square',
      'instagram',
      'yuque',
      'alibaba',
      'yahoo',
      'reddit',
      'sketch',
      // 网站通用图标
      'account-book',
      'alert',
      'api',
      'appstore',
      'audio',
      'bank',
      'bell',
      'book',
      'bug',
      'bulb',
      'calculator',
      'build',
      'calendar',
      'camera',
      'car',
      'carry-out',
      'cloud',
      'code',
      'compass',
      'contacts',
      'container',
      'control',
      'credit-card',
      'crown',
      'customer-service',
      'dashboard',
      'database',
      'dislike',
      'environment',
      'experiment',
      'eye-invisible',
      'eye',
      'file-add',
      'file-excel',
      'file-exclamation',
      'file-image',
      'file-markdown',
      'file-pdf',
      'file-ppt',
      'file-text',
      'file-unknown',
      'file-word',
      'file-zip',
      'file',
      'filter',
      'fire',
      'flag',
      'folder-add',
      'folder-open',
      'folder',
      'frown',
      'funnel-plot',
      'gift',
      'hdd',
      'heart',
      'home',
      'hourglass',
      'idcard',
      'insurance',
      'interaction',
      'layout',
      'like',
      'lock',
      'mail',
      'medicine-box',
      'meh',
      'message',
      'mobile',
      'money-collect',
      'pay-circle',
      'notification',
      'phone',
      'picture',
      'play-square',
      'printer',
      'profile',
      'project',
      'pushpin',
      'property-safety',
      'read',
      'reconciliation',
      'red-envelope',
      'rest',
      'rocket',
      'safety-certificate',
      'save',
      'schedule',
      'security-scan',
      'setting',
      'shop',
      'shopping',
      'skin',
      'smile',
      'sound',
      'star',
      'switcher',
      'tablet',
      'tag',
      'tags',
      'tool',
      'thunderbolt',
      'trophy',
      'unlock',
      'usb',
      'video-camera',
      'wallet',
    ],
  },
  tabler: {
    name: 'Tabler Icons',
    prefix: 'tabler',
    icons: [
      // 工作流核心图标
      'workflow',
      'git-branch',
      'git-merge',
      'git-pull-request',
      'git-commit',
      'git-fork',
      'git-compare',
      'timeline',
      'timeline-event',
      'route',
      'route-2',
      'sitemap',
      'hierarchy',
      'hierarchy-2',
      'hierarchy-3',
      'network',
      'topology-star',
      'topology-ring',
      'topology-bus',
      'topology-complex',
      'topology-full',
      'topology-star-2',
      'topology-star-3',
      'share',
      'share-2',
      'share-3',
      'arrows-split',
      'arrows-split-2',
      'arrows-join',
      'arrows-join-2',
      'arrows-shuffle',
      'arrows-shuffle-2',
      'arrows-transfer-down',
      'arrows-transfer-up',
      'arrows-exchange',
      'arrows-exchange-2',
      'arrows-sort',
      'arrows-move',
      'arrows-move-horizontal',
      'arrows-move-vertical',
      // 流程控制
      'player-play',
      'player-pause',
      'player-stop',
      'player-skip-forward',
      'player-skip-back',
      'player-track-next',
      'player-track-prev',
      'repeat',
      'repeat-once',
      'refresh',
      'refresh-alert',
      'refresh-dot',
      'reload',
      'rotate',
      'rotate-clockwise',
      'rotate-2',
      'rotate-360',
      'arrows-right-left',
      'arrows-up-down',
      'arrows-left-right',
      'arrows-down-up',
      // 状态图标
      'circle',
      'circle-dot',
      'circle-check',
      'circle-x',
      'circle-plus',
      'circle-minus',
      'square',
      'square-check',
      'square-x',
      'square-plus',
      'square-minus',
      'square-dot',
      'hexagon',
      'octagon',
      'triangle',
      'diamond',
      'pentagon',
      'loader',
      'loader-2',
      'loader-3',
      'loader-quarter',
      'hourglass',
      'hourglass-empty',
      'hourglass-high',
      'hourglass-low',
      'clock',
      'clock-hour-1',
      'clock-hour-2',
      'clock-hour-3',
      'clock-hour-4',
      'alarm',
      'bell',
      'bell-ringing',
      'bell-plus',
      'bell-minus',
      'bell-x',
      'bell-check',
      // 文档和文件
      'file',
      'file-text',
      'file-check',
      'file-x',
      'file-plus',
      'file-minus',
      'file-search',
      'file-code',
      'file-certificate',
      'file-analytics',
      'file-report',
      'file-invoice',
      'files',
      'folder',
      'folder-open',
      'folder-plus',
      'folder-minus',
      'folder-x',
      'folders',
      'clipboard',
      'clipboard-check',
      'clipboard-list',
      'clipboard-text',
      'clipboard-data',
      'notes',
      'note',
      'notebook',
      'report',
      'report-analytics',
      'report-medical',
      'report-money',
      'report-search',
      // 用户和团队
      'user',
      'user-check',
      'user-plus',
      'user-minus',
      'user-x',
      'users',
      'users-group',
      'user-circle',
      'user-exclamation',
      'user-search',
      'user-edit',
      'id',
      'id-badge',
      'id-badge-2',
      'badge',
      'badges',
      'shield',
      'shield-check',
      'shield-x',
      'shield-lock',
      'lock',
      'lock-open',
      'lock-access',
      'key',
      'fingerprint',
      // 数据和分析
      'chart-line',
      'chart-bar',
      'chart-pie',
      'chart-donut',
      'chart-area',
      'chart-dots',
      'chart-arcs',
      'chart-candle',
      'chart-radar',
      'chart-sankey',
      'chart-treemap',
      'chart-infographic',
      'database',
      'database-import',
      'database-export',
      'server',
      'server-2',
      'cloud',
      'cloud-upload',
      'cloud-download',
      'api',
      'api-app',
      'webhook',
      'code',
      'code-plus',
      'code-minus',
      'terminal',
      'terminal-2',
      // 设置和工具
      'settings',
      'adjustments',
      'adjustments-horizontal',
      'tool',
      'tools',
      'wrench',
      'hammer',
      'build',
      'puzzle',
      'puzzle-2',
      'components',
      'layout',
      'layout-2',
      'layout-grid',
      'layout-list',
      'layout-kanban',
      'layout-board',
      'layout-sidebar',
      'layout-navbar',
      'template',
      'box',
      'package',
      'packages',
      // 通信和消息
      'message',
      'message-2',
      'message-circle',
      'message-dots',
      'messages',
      'mail',
      'mail-opened',
      'inbox',
      'send',
      'phone',
      'phone-call',
      'video',
      'microphone',
      'speakerphone',
      'broadcast',
      'rss',
      'notification',
      // 商业和金融
      'shopping-cart',
      'shopping-bag',
      'credit-card',
      'coin',
      'currency-dollar',
      'currency-euro',
      'currency-pound',
      'currency-yen',
      'receipt',
      'calculator',
      'chart-pie-2',
      'businessplan',
      'presentation',
      'presentation-analytics',
      'building',
      'building-store',
      'building-bank',
      'home',
      'briefcase',
      // 导航和位置
      'map',
      'map-2',
      'map-pin',
      'location',
      'compass',
      'navigation',
      'direction',
      'directions',
      'route-alt-left',
      'route-alt-right',
      'current-location',
      'gps',
      // 媒体和创意
      'photo',
      'camera',
      'video-camera',
      'music',
      'palette',
      'color-picker',
      'brush',
      'pencil',
      'edit',
      'eraser',
      'marquee',
      'crop',
      'transform',
      // 系统和设备
      'device-desktop',
      'device-laptop',
      'device-tablet',
      'device-mobile',
      'devices',
      'cpu',
      'memory',
      'hard-drive',
      'usb',
      'bluetooth',
      'wifi',
      'signal',
      'battery',
      'plug',
      'power',
    ],
  },
};

// 当前图标集
const currentIconSet = computed(
  () => iconSets[activeTab.value as keyof typeof iconSets],
);

// 过滤后的图标列表
const filteredIcons = computed(() => {
  if (!searchText.value) {
    return currentIconSet.value.icons;
  }
  return currentIconSet.value.icons.filter((icon) =>
    icon.toLowerCase().includes(searchText.value.toLowerCase()),
  );
});

// 显示的图标值
const displayValue = computed(() => {
  if (!props.value) return '';
  return props.value;
});

// 监听外部值变化
watch(
  () => props.value,
  (newVal) => {
    selectedIcon.value = newVal || '';
  },
  { immediate: true },
);

// 打开选择器
function openPicker() {
  visible.value = true;
  selectedIcon.value = props.value || '';
  searchText.value = '';
}

// 选择图标
function selectIcon(icon: string) {
  const fullIcon = `${currentIconSet.value.prefix}:${icon}`;
  selectedIcon.value = fullIcon;
}

// 确认选择
function handleOk() {
  emit('update:value', selectedIcon.value);
  emit('change', selectedIcon.value);
  visible.value = false;
}

// 取消选择
function handleCancel() {
  visible.value = false;
  searchText.value = '';
}

// 清空选择
function clearIcon() {
  emit('update:value', '');
  emit('change', '');
}
</script>

<template>
  <div class="icon-picker">
    <div class="flex gap-2">
      <Input
        :value="displayValue"
        placeholder="请选择图标"
        readonly
        @click="openPicker"
        class="flex-1 cursor-pointer"
      >
        <template #prefix>
          <IconifyIcon
            v-if="displayValue"
            :icon="displayValue"
            class="text-lg"
          />
        </template>
      </Input>
      <a-button v-if="displayValue" @click="clearIcon">清空</a-button>
    </div>

    <Modal
      v-model:open="visible"
      title="选择图标"
      width="800px"
      :body-style="{ maxHeight: '600px', overflowY: 'auto' }"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <div class="mb-4">
        <Input v-model:value="searchText" placeholder="搜索图标..." allow-clear>
          <template #prefix>
            <Search :size="16" />
          </template>
        </Input>
      </div>

      <Tabs v-model:active-key="activeTab">
        <TabPane v-for="(set, key) in iconSets" :key="key">
          <template #tab>
            <span>
              {{ set.name }}
              <span class="ml-1 text-xs text-gray-400">({{ set.icons.length }})</span>
            </span>
          </template>
          <div v-if="filteredIcons.length > 0">
            <div class="mb-2 text-xs text-gray-500">
              找到 {{ filteredIcons.length }} 个图标
            </div>
            <div class="grid grid-cols-8 gap-2">
              <div
                v-for="icon in filteredIcons"
                :key="icon"
                class="flex cursor-pointer flex-col items-center justify-center rounded border p-3 transition-all hover:bg-blue-50 hover:shadow-sm"
                :class="[
                  selectedIcon === `${set.prefix}:${icon}`
                    ? 'border-blue-500 bg-blue-100 shadow-md'
                    : 'border-gray-200',
                ]"
                @click="selectIcon(icon)"
                :title="`${set.prefix}:${icon}`"
              >
                <IconifyIcon
                  :icon="`${set.prefix}:${icon}`"
                  class="mb-1 text-2xl"
                />
                <span class="w-full truncate text-center text-xs text-gray-500">
                  {{ icon }}
                </span>
              </div>
            </div>
          </div>
          <Empty v-else description="没有找到匹配的图标" />
        </TabPane>
      </Tabs>
    </Modal>
  </div>
</template>

<style scoped>
:deep(.ant-input) {
  cursor: pointer;
}
</style>
